<template>
  <div>
    <VersionTypeSelect :disabled="disabled" v-model="versionType" class="version-type-select" :append-to-body="appendToBody" :getPopupContainer="getPopupContainer" v-if="!onlyVersionType" style="width: 80px;"/>
    <a-select
      show-search
      option-filter-prop="children"
      :filter-option="filterOption"
      :placeholder="$t('pleaseSelect') + '【'+$store.getters.getDictCodeObj('versionTypeDictCode')[versionType]+'】' + placeHolder"
      :allow-clear="clear"
      :mode="mode"
      :disabled="disabled"
      :maxTagCount="maxTagCount"
      v-model="selectedValue"
      :class="onlyVersionType ? '' : 'join-select-after'"
      :style="{width: onlyVersionType ? '100%' : showPackageType ? 'calc(100% - 180px)': 'calc(100% - 80px)'}"
      :getPopupContainer="getPopupContainerWrapper"
      @dropdownVisibleChange="(val) => {
        if(val){
          getData()
        }
      }"
    >
      <a-spin v-if="fetching" slot="notFoundContent" size="small" />
      <a-select-option
        v-for="(item, index) in options"
        :key="'version-'+item[replaceFields.key]"
        :value="item[replaceFields.value]"
        :title="getVersionTypeText(item[replaceFields.title], item.versionType)"
      >{{ item[replaceFields.title]&&item.versionType?getVersionTypeText(item[replaceFields.title], item.versionType): '版本号' + ' 【版本类型】 ' }}</a-select-option>
    </a-select>
    <PackageTypeSelect :disabled="disabled" v-model="packageType" class="join-select-after" @change="changePackageType" :append-to-body="appendToBody" :getPopupContainer="getPopupContainer" v-if="!onlyVersionType && showPackageType" style="width: 80px; margin-left:5px"/>
  </div>
</template>
<script>
  // 所有车型(车型代码、车型名称)列表
  import VersionTypeSelect from './VersionTypeSelect'
  import Vue from 'vue'
  import {mapState} from "vuex";
  import PackageTypeSelect from './PackageTypeSelect.vue';

  Vue.$store.dispatch('getVersionTypeDictCodeData');
  export default {
    components: {
      VersionTypeSelect,
      PackageTypeSelect
    },
    props: {
      packageStrategy:{
        type: String,
        default:''
      },
      showPackageType:{
        type: Boolean,
        default: false
      },
      mode: {
        type: String,
        default: 'default'
      },
      defaultValue: {
        type: [String, Array, Object, undefined],
        default () {
          return undefined
        }
      },
      defaultTitle: {
        type: [String, Array, Object, undefined],
        default () {
          return undefined
        }
      },
      /**
       * 已选中数据，用于未加载数据时展示
       */
      defaultData: {
        type: [String, Array, Object, undefined],
        default () {
          return undefined
        }
      },
      lazyLoad:{
        type: Boolean,
        default: false
      },
      maxTagCount: {
        type: Number,
        default: 3
      },
      disabled: {
        type: Boolean,
        default: false
      },
      clear: {
        type: Boolean,
        default: false
      },
      ecuModuleId: {
        type: String,
        default: ''
      },
      targetVersionId: {
        type: String,
        default: ''
      },
      /**
       * 指定后，版本类型下拉框将不展示
       */
      onlyVersionType:{
        type: String,
        default: ''
      },
      /**
       * 版本下拉框默认选中
       */
      defaultVersionType:{
        type: String,
        default: ''
      },
      /**
       * 版本归属： ecu、configFile
       */
      versionBelong:{
        type: String,
        default: 'ecu'
      },
      appendToBody: {
        type: Boolean,
        default: false
      },
      getPopupContainer: {
        type: Function,
        default: undefined
      },
      // 要替换取每个项的属性对应的key
      replaceFields: {
        type: Object,
        default () {
          return {
            key: 'id',
            value: 'id',
            title: 'name'
          }
        }
      },
      initFunction: {
        type: Boolean,
        default: false
      },
      placeHolder: {
        type: String,
        default(){
          return this.$t('originalVersion');
        }
      }
    },
    model: {
      prop: "defaultValue", //绑定的值，通过父组件传递
      event: "change" //自定义事件名
    },
    computed: {
      selectedValue:{
        get() {
          return this.defaultValue;
        },
        set(val) {
          this.$emit('change', val);    // 触发
          this.changeOption(val)
        }
      }
    },
    data () {
      return {
        options: [],
        fetching: false,
        versionType: this.onlyVersionType || this.defaultVersionType || 'TEST',
        packageType:this.packageStrategy
      }
    },
    watch: {
      packageStrategy:{
        handler(val){
          if(val){
            this.packageType=val
          }
        }
      },
      'query.time': {
        handler (v, o) {
          // this.getData()
        },
        immediate: true
      },
      ecuModuleId(val, old) {
        if (old) {
          this.selectedValue = undefined;
        }
        if (!this.lazyLoad && this.options.length === 0) {
          this.getData();
        }
      },
      versionType() {
        this.selectedValue = undefined
        if(!this.lazyLoad && this.options.length === 0){
          this.getData();
        }
      }
    },
    created () {
      if (this.initFunction) {
        this.getData();
      }
      if (this.defaultData) {
        this.options = this.defaultData instanceof Array ? this.defaultData : [this.defaultData];
      }else if (!this.lazyLoad) {
        this.getData();
      }
    },
    methods: {
      changePackageType(val){
        this.$emit('changPackageType',val)
      },
      getPopupContainerWrapper (triggerNode) {
        if (this.getPopupContainer) {
          return this.getPopupContainer(triggerNode);
        }
        if (!this.appendToBody && triggerNode) {
          return triggerNode.parentNode
        } else {
          return window.document.body
        }
      },
      getData (ids) {
        if (!this.ecuModuleId || !this.versionType) {
          this.options=[];
          return;
        }
        this.fetching = true;
        let api = this.versionBelong === 'ecu' ? 'allVersion' : 'configFileSelect';
        let params = { ecuModuleId:this.ecuModuleId, targetVersionId: this.targetVersionId, versionType: this.versionType };
        if (ids) {
          params.ids = ids instanceof Array ? ids : [ids];
        }
        this.$api[api](params)
          .then(response => {
            this.options = response.data || []
            this.fetching = false;
          });
      },
      changeOption (val) {
        if (val instanceof Array) {
          let selectedItems = val.map((item) => {
            return this.options.find(e => e.id === item);
          });
          this.$emit('changeOption', val, selectedItems)
          return;
        }
        let item = this.options.find(e => e.id === val);
        this.$emit('changeOption', val, item)
      },
      getVersionTypeText(name, versionType) {
        return name + ' 【' +
          (this.$store.getters.getDictCodeObj('versionTypeDictCode')[versionType] || versionType)
          + '】 ';
      },
      filterOption (input, option) {
        return (
          option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
        )
      }
    }
  }
</script>
<style lang="less">
  .version-type-select{
    div{
      border-radius: 4px 0 0 4px;border-right: 0;
    }
  }
  .join-select-after{
    div{
      border-radius: 0 4px 4px 0;
    }
  }
</style>
